﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using StudentManagement.Filter;
using StudentManagement.Models;
using StudentManagement.ViewModel;

namespace StudentManagement.Controllers
{
    public class HomeController : Controller
    {
        private readonly IStudentRepository _studentRepository;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly ILogger _logger;

        public HomeController(IStudentRepository studentRepository, IWebHostEnvironment webHostEnvironment,ILogger<HomeController> logger)
        {
            _studentRepository = studentRepository;
            _webHostEnvironment = webHostEnvironment;
            _logger = logger;
        }


        //[Route("")] //相当于http://localhost/ 网站根路径
        //[Route("/Home")]
        //[Route("/Home/Index")]
        //返回学生的名字
        public ViewResult Index()
        {
            //查询所有的学生信息
            var model = _studentRepository.GetAllStudents();
            //将学生列表传递到视图
            return View("~/Views/Home/Index.cshtml", model);
        }

        /* [Route("/Home/Details/{id?}")]  *///{id?}参数后加"?",代表该参数可空
        public IActionResult Details(int id)
        {

            //.net core自带的:LogLevel=>日志级别枚举,对应的方法:
            //public enum LogLevel
            //{
            //   Trace = 0,      对应->   _logger.LogTrace();
            //   Debug = 1,              _logger.LogDebug();
            //   Information = 2,        _logger.LogInformation();
            //   Warning = 3,            _logger.LogWarning();
            //   Error = 4,              _logger.LogError();
            //   Critical = 5,           _logger.LogCritical();
            //   None = 6                //无提供方法
            //}

            _logger.LogTrace("Trace(跟踪) Log");
            _logger.LogDebug("Debug(调试) Log");
            _logger.LogInformation("信息(Information) Log");
            _logger.LogWarning("警告(Warning) Log");
            _logger.LogError("错误(Error) Log");
            _logger.LogCritical("严重(Criticl) Log");


            //throw new Exception("此异常发生在/Home/Details视图中");

            //Student model = _studentRepository.GetStudent(1);
            //return new ObjectResult(model);

            //return View("~/MyViews/Test.cshtml");
            //return View("MyViews/Test.cshtml");
            //return View("/MyViews/Test.cshtml");

            Student model = _studentRepository.GetStudent(id);

            if (model==null)
            {
                Response.StatusCode = 404;
                return View("StudentNotFound",id);
            }


            return View(model);
        }


        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }



        [HttpPost]
        [ModelStateFilter]
        public IActionResult Create(StudentCreateViewModel model)
        {


            string uniqueFileName = null;

            //单文件上传
            if (model.Photo != null)
            {
                //string uploadFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images");

                //uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
                //string filePath = Path.Combine(uploadFolder, uniqueFileName);


                //model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));



                uniqueFileName = ProcessUploadedFile(model);

            }

            //多文件上传
            //if (model.Photos != null && model.Photos.Count>0)
            //{

            //    foreach (var photo in model.Photos)
            //    {
            //        string uploadFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images");

            //        uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName;
            //        string filePath = Path.Combine(uploadFolder, uniqueFileName);


            //        photo.CopyTo(new FileStream(filePath, FileMode.Create));
            //    }

            //}


            Student newstudent = new Student()
            {
                ClassName = model.ClassName,
                Email = model.Email,
                Name = model.Name,
                photopath = uniqueFileName
            };

            _studentRepository.Add(newstudent);


            return RedirectToAction("details", new { id = newstudent.Id });


            //if (ModelState.IsValid)
            //{
            //var newStudent = _studentRepository.Add(student);

            //return RedirectToAction("details", new { id = newStudent.Id });
            //}

            //return View();

        }


        [HttpGet]
        public ViewResult Edit(int id)
        {
            Student student = _studentRepository.GetStudent(id);

            //if (student!=null)
            //{
            StudentEditViewModel studentEditViewModel = new StudentEditViewModel()
            {
                ClassName = student.ClassName,
                Email = student.Email,
                existingPhotoPath = student.photopath,
                Id = student.Id,
                Name = student.Name
            };


            return View(studentEditViewModel);
            //}

            //throw new Exception("查询不到这个学生信息!");

        }

        [HttpPost]
        public IActionResult Edit(StudentEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                Student student = _studentRepository.GetStudent(model.Id);

                student.Email = model.Email;
                student.Name = model.Name;
                student.ClassName = model.ClassName;


                if (model.Photo != null)
                {
                    string filepath = Path.Combine(_webHostEnvironment.WebRootPath, "images", model.existingPhotoPath);
                    System.IO.File.Delete(filepath);


                    //string uploadFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images");

                    //uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
                    //string filePath = Path.Combine(uploadFolder, uniqueFileName);


                    //model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));


                    student.photopath = ProcessUploadedFile(model);
                }


                Student updateStudent = _studentRepository.Update(student);



                return RedirectToAction("Index");
            }


            return View(model);

        }

        /// <summary>
        /// 将照片保存到指定的路径中,并返回唯一的文件名
        /// </summary>
        /// <returns></returns>
        private string ProcessUploadedFile(StudentCreateViewModel model)
        {
            string uniqueFileName = null;

            string uploadFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images");

            uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
            string filePath = Path.Combine(uploadFolder, uniqueFileName);

            //因为使用了非托管资源,所以需要手动进行释放
            using (FileStream fs= new FileStream(filePath, FileMode.Create))
            {
                model.Photo.CopyTo(fs);
            }

            return uniqueFileName;

        }



        public IActionResult abc()
        {
            string str = 123456789111.ToString("00000000");

            return View();
        }
    }
}